
<template>
  <div>
    <!-- 头部 -->
    <section class="shortcut w">
      <div>
        <div class="fl">
          <ul>
            <li class="Logo"><el-link
              @click="reloadIndex()"
            ><img src="@/assets/BookLogo.png"></el-link></li>
            <li><router-link
              v-if="userId"
              :to="{path: '/shoppingCar', name: 'userShopCar'}"
            >我的购物车</router-link> &nbsp; </li>
            <li><router-link
              v-if="userId"
              :to="{path: '/booksOrder', name: 'userBookOrder'}"
            >订单管理</router-link> &nbsp; </li>
          </ul>
        </div>
        <div>
          <form class="search">
            <el-input v-model="input" placeholder="请输入内容" />
            <el-button @click="search(input,currentPage),clickHandler($event)">搜索</el-button>
          </form>
        </div>
        <div class="userInfo">
          <!-- el-dropdown中没有el-dropdown-menu会报错 -->
          <el-dropdown v-if="userName !== '登录'">
            <span class="el-dropdown-link">
              <router-link to="/userLogin">{{ userName }}</router-link><i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="logOut()">登出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <router-link v-else to="/userLogin">{{ userName }}</router-link>
        </div>
      </div>
    </section>
    <!-- 主体 -->
    <div class="w">
      <div class="classify fl">
        <el-col :span="12">
          <p
            index="1"
            :style="{
              width: '200px',
              height: '40px',
              lineHeight: '40px',
              backgroundColor: '#fff',
              border: '1px solid #ddd',
              borderRadius: '4px',
              paddingLeft: '20px',
              fontSize: '14px'
            }"
          >
            所有分类
          </p>

          <el-menu
            class="el-menu-vertical-demo"
            background-color="#dff0d8"
            text-color="#41ae3c"
            :style="{
              width: '200px',
            }"
          >

            <el-submenu v-for="category in categorys" :key="category.id" :index="category.id + ''">
              <span slot="title">{{ category.title }}</span>
              <el-menu-item-group>
                <el-menu-item v-for="subCategory in category.children" :key="subCategory.id" :index="subCategory.id + ''" @click="seachByCategory(subCategory.id,category.id)">{{ subCategory.title }}</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
        </el-col>

        <el-col :span="12">
          <p
            index="1"
            :style="{
              width: '200px',
              height: '40px',
              marginTop: '50px',
              lineHeight: '40px',
              backgroundColor: '#fff',
              border: '1px solid #ddd',
              borderRadius: '4px',
              paddingLeft: '20px',
              fontSize: '14px'
            }"
          >
            热销榜单
          </p>

          <el-collapse
            accordion
            :style="{
              border: '1px solid #ddd',
              borderRadius: '4px',
              borderTop: 'none'
            }"
          >
            <el-collapse-item v-for="book in rankingBooks" :key="book[0].id">
              <template slot="title" :style="{paddingLeft: '4px'}">
                {{ book[0].bookName }}
              </template>
              <div>作者: {{ book[0].author }}</div>
              <div>价格: {{ book[0].price }}</div>
              <router-link
                :style="{fontSize: '14px'}"
                :to="{path: '/bookInfo?id=' + book[0].id}"
              >查看详情</router-link>
            </el-collapse-item>
          </el-collapse>
        </el-col>

      </div>
      <div class="booksInfo fl" style="margin-left: 80px">
        <el-row class="fl clearfix">
          <el-col v-for="post in posts" :key="post.id" :span="4" :offset="1" class="fl clearfix" :style="{marginTop: '2%'}">
            <router-link :to="{path: '/bookInfo', name: 'userBookInfo', query: { id: post.id } }">
              <el-card :body-style="{ padding: '0px'}" class="fl clearfix" shadow="hover">
                <img :src="post.cover" class="image" :style="{width: '235px', height: '236px'}">
                <div style="padding: 14px;">
                  <p :style="{color: 'red', fontSize: '20px', fontWeight: 800}">￥{{ post.price }}</p>
                  <p :style="{fontSize: '18px', fontWeight: 800}">{{ post.bookName }}</p>
                  <p> 作者：{{ post.author }}</p>
                  <p>出版社：{{ post.press }}</p>
                  <p style="width: 208px ;text-overflow:ellipsis; white-space:nowrap; overflow:hidden;">出版时间：{{ post.publishingTime }}</p>
                </div>
              </el-card>
            </router-link>
          </el-col>
        </el-row>

      </div>
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="allbookNum"
        :style="{
          position: 'relative',
          bottom: '0',
          left: '50%',
          transform: 'translateX(-50%)',
          marginTop: '20px',
          float: 'left',
        }"
        @current-change="page"
      />
      <div
        class="fl"
        :style="{
          position: 'relative',
          bottom: '0',
          marginTop: '40px',
          width: '100%',
          height: '1px'
        }"
      />
    </div>

  </div>
</template>
<script>
import userApi from '@/api/user'

export default {
  inject: ['reload'],
  data() {
    return {
      posts: [],
      input: '',
      pageSize: 12,
      categorys: '',
      user: false,
      userId: 0,
      userName: '登录',
      currentPage: 0,
      allbookNum: 0,
      rankingIds: {},
      rankingBooks: []
    }
  },
  created: async function() {
    this.userName = '登录'
    this.userId = window.sessionStorage.getItem('token')
    // 接收user相关参数
    if (this.userId) this.userName = window.sessionStorage.getItem('name')
    this.initData()
  },
  methods: {
    reloadIndex() {
      this.reload()
    },
    async initData() {
      // 获取销量排名前三的书籍
      await userApi.ranking().then(resp => {
        this.rankingIds = Object.entries(resp.data.data.rank)
        this.rankingIds.sort((a, b) => { return b[1] - a[1] })
      }, err => {
        console.log(err)
      })
      // 循环中的异步操作需要async + await确保输出顺序
      // 并且这里不适合使用forEach遍历,forEach内部封装了while（async + await不起作用）
      for (let i = 0; i < this.rankingIds.length; i++) {
        await userApi.getBookById(this.rankingIds[i][0].toString()).then(resp => {
          this.rankingBooks.push(Object.values(resp.data.data))
        },
        err => {
          console.log(err)
        })
      }
      // 获取各类信息
      userApi.getPage(1).then(resp => {
        this.posts = resp.data.data.books
      }, err => {
        console.log(err)
      })
      userApi.getAllCategory().then(resp => {
        this.categorys = resp.data.data.data
      }, err => {
        console.log(err)
      })
      userApi.getAllbooks().then(resp => {
        this.allbookNum = resp.data.data.books.length
      }, err => {
        console.log(err)
      })
    },
    // 登出，即删除sessionStorage中的token
    async logOut() {
      window.sessionStorage.removeItem('token')
      this.userName = '登录'
      this.userId = 0
      await userApi.Userlogout().then(resp => {
        this.$message.success('已注销!')
      }, err => {
        console.log(err)
      })
    },
    // 点击获取当前分页下的图书
    page(currentPage) {
      if (!this.input) {
        userApi.getPage(currentPage).then(resp => {
          this.posts = resp.data.data.books
        }, err => {
          console.log(err)
        })
      } else {
        this.search(this.input, currentPage)
      }
    },
    search(input, currentPage) {
      userApi.selectByCondition(input, currentPage).then(resp => {
        this.posts = resp.data.data.books.records
        // 接口暂无  返回全部搜索条件下的图书  先写死
        this.pageSize = resp.data.data.books.size
        this.allbookNum = resp.data.data.books.total
      }, err => {
        console.log(err)
      })
    },
    seachByCategory(subId, parentId) {
      userApi.getbookbyCategory(parentId, subId).then(resp => {
        this.posts = resp.data.data.books
        // 调整分页按钮对应参数
        this.pageSize = Object.keys(resp.data.data.books).length
        this.allbookNum = Object.keys(resp.data.data.books).length
      }, err => {
        console.log(err)
      })
    }
  }
}

</script>

<style scoped>

.Logo img {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 50px;
  height: 50px;
  text-align: center;
}

.search {
  position: absolute;
  width: 300px;
  height: 40px;
  top: 0;
  right: 150px;
}

.el-input {
  width: 200px;
  height: 30px;
}

.el-input__inner {
  height: 30px;
  width: 200px;
}

.el-button {
  position: absolute;
  top: 5px;
  right: 40px;
  width: 50px;
  height: 30px;
  padding: 0;
}

.userInfo {
  position: absolute;
  right: 100px;
  font-size: 16px;
}

.classify {
  width: 200px;
  margin: 25px 0 0;
}

.el-submenu {
  border-bottom: 1px solid #ddd;
}

.el-menu-item-group__title {
  padding: 0;
}

.el-col-12 {
/* 分类栏长宽 */
  width: 200px;
}

.el-col-8 {
  width: 25%;
  /* margin-left: 5px; */
}

.booksInfo {
  width: 80%;
}

.el-col-offset-1 {
  margin-left: 1%;
}

.el-col-4 {
  float: left;
  width: 24%;
}

.el-row {
  width: 100%
}

.el-card:hover {
  box-shadow: 0px 15px 30px 2px rgba(0, 0, 0, .1);
	transform: translate(0,-5px);
  transition: all .5s;
}

.el-collapse-item >>> .el-collapse-item__header {
  padding-left: 20px;
}

.el-collapse-item >>> .el-collapse-item__content *{
  padding-left: 20px;
  padding-bottom: 10px;
}

</style>
